package com.yuneec.droneservice.command;

import com.yuneec.droneservice.model.ControllerVersion;
import com.yuneec.droneservice.request.IResponse;
import com.yuneec.droneservice.utils.ByteUtils;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;

/**
 * Created by gjw on 2017/3/27.
 */

public class GetControllerVersion extends BaseCommand {


    public GetControllerVersion() {
        super(MAV_RC_COMMAND.MAV_RC_CMD_GET_VERSION);
    }

    @Override
    public IResponse<ControllerVersion> toResponse(byte[] data, int off, int payloadLen) {
        int code = data[off + 1] & 0xff;
        IResponse<ControllerVersion> response = new IResponse(ids(), code);
        if (code == MAV_RC_ERROR_CODE.MAV_RC_ERR_SUCCESS) {
            int len = ByteUtils.byteArrayToShort(Arrays.copyOfRange(data, off + 2, off + 4), IS_BIGENDIAN);
            ControllerVersion version = new ControllerVersion();
            if (len > 0) {
                try {
                    version.setHardwareVersion(new String(Arrays.copyOfRange(data, off + 4, off + 4 + len), "utf8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            int skip = 4 + len;
            len = ByteUtils.byteArrayToShort(Arrays.copyOfRange(data, off + skip, off + skip + 2), IS_BIGENDIAN);
            if (len > 0) {
                try {
                    version.setFirmwareVersion(new String(Arrays.copyOfRange(data, off + skip + 2, off + skip + 2 + len), "utf8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            skip = skip + 2 + len;
            len = ByteUtils.byteArrayToShort(Arrays.copyOfRange(data, off + skip, off + skip + 2), IS_BIGENDIAN);
            if (len > 0) {
                try {
                    version.setMcuVersion(new String(Arrays.copyOfRange(data, off + skip + 2, off + skip + 2 + len), "utf8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            response.setParam(version);
        }
        return response;
    }

}
